package com.moon.game.proxy;

import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.io.UnsupportedEncodingException;

import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.DynamicChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;

import com.moon.game.constants.GlobalConstants;
import com.moon.game.exception.GException;
import com.moon.game.message.ObjMessage;


/**
 * @author Ranger 作者 E-mail:haozi000005@163.com
 * @version 创建时间：2012-4-22 下午4:03:35
 * @description 
 */
public class ProxyShow {
	private static final Logger log = Logger.getLogger(ProxyShow.class);
	
	/**
	 * 简单返回状态后直接关闭通道
	 * 
	 * @param channel
	 * @param status
	 */
	public static void outResponseStatu(Channel channel, HttpResponseStatus status) {
		HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
		channel.write(response).addListener(ChannelFutureListener.CLOSE);
	}
	
	/**
	 * 输出html页面
	 * 
	 * @param channel
	 * @param content
	 */
	private static void showFtl(Channel channel, String content) {
		HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
		// 设置body数据
		ChannelBuffer buffer = new DynamicChannelBuffer(2048);
		try {
			buffer.writeBytes(content.getBytes(GlobalConstants.UTF_8));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		response.setContent(buffer);

		// 设置浏览器header
		response.setHeader("Content-Type", "text/vnd.wap.wml; charset=" + GlobalConstants.UTF_8);
		response.setHeader("Content-Length", response.getContent().writerIndex());

		// Close the connection as soon as the error message is sent.
		channel.write(response).addListener(ChannelFutureListener.CLOSE);
	}
	
	/**
	 * 显示结果
	 * 
	 * @param reqSession
	 * @param resp
	 * @throws GException
	 */
	public static void showResult(Channel channel, ObjMessage resp) throws GException {
		String content = "";
		content = ProxyUtil.parseFtl(resp);
		showFtl(channel, content);
	}
	
	/**
	 * 显示错误页面
	 * 
	 * @param channel
	 * @param resp
	 * @throws GException
	 */
	public static void showError(Channel channel, ObjMessage resp) throws GException{
		String content = "";
		content = ProxyUtil.parseFtl(resp);
		showFtl(channel, content);
	}
}
